﻿using CWCS.Common.Log;
using CWCS.Core.Library.ScanManager;
using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;

namespace CWCS.BLL
{
    public class ScanBLL : BLLBase
    {
        KeyenceReaderService service = new KeyenceReaderService();
        int sacnCount = int.Parse(ConfigurationManager.AppSettings["ScanCount"].ToString().Trim());
        int sacnSendTimeOut = int.Parse(ConfigurationManager.AppSettings["SendTimeOut"].ToString().Trim());
        int sacnReceiveTimeOut = int.Parse(ConfigurationManager.AppSettings["ReceiveTimeOut"].ToString().Trim());
        private LogHelper scanlog = new LogHelper("Scan");
        /// <summary>
        /// Author:Wesky 
        /// CreateTime:2021-12-01, 10:37:22  
        /// Description:  扫码器连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Connection(string ip, int port, string station)
        {
            try
            {
                TcpClientInfo clientInfo = new TcpClientInfo();
                clientInfo.Ip = IPAddress.Parse(ip); // 扫码器IP
                clientInfo.Port = port; // 扫码器端口号
                clientInfo.Count = sacnCount;  // 没扫到码重试次数
                clientInfo.SendTimeOut = sacnSendTimeOut; // 请求超时 毫秒
                clientInfo.ReceiveTimeOut = sacnReceiveTimeOut; // 接收扫码内容超时 毫秒
                clientInfo.ReaderNo = station;  // 扫码器编号  自定义
                _tcpClientInfo.GetOrAdd(station, clientInfo);

                var res = service.Connection(ref clientInfo);  // 建立通信。建立成功以后，默认为长连接。后续操作也只需传递该 clientInfo 实例
                if (!res.IsSucceed)
                {
                    scanlog.Info("与基恩士扫码器建立通信连接失败!" + "地址:" + ip + ",端口:" + port);
                }
                else
                {
                    scanlog.Info("与基恩士扫码器建立通信连接成功!" + "地址:" + ip + ",端口:" + port);
                }
            }
            catch (Exception ex)
            {
                scanlog.Info("与基恩士扫码器建立通信连接异常!" + ex.Message + "地址:" + ip + ",端口:" + port);
            }
        }

        /// <summary>
        /// Author:Wesky 
        /// CreateTime:2021-12-01, 10:36:47  
        /// Description:  开始扫码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public string BeginReader(string station)
        {
            var clientInfo = _tcpClientInfo[station];
            string scanInfo = string.Empty;
            try
            {
                int now = 0;
                while (now++ < sacnCount)
                {
                    var res = service.ReadBarcode(ref clientInfo);
                    if (!res.IsSucceed)
                    {
                        scanlog.Info("第" + now + "次扫码，扫码失败!" + res.Message);
                    }
                    else
                    {
                        scanlog.Info("第" + now + "次扫码，扫码成功!扫码耗时" + res.ElapsedMilliseconds + ",扫到的码:" + res.Value);
                        return res.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                scanlog.Info("扫码发生异常" + ex.Message);
            }
            return scanInfo;
        }

        /// <summary>
        /// Author:Wesky 
        /// CreateTime:2021-12-01, 10:36:47  
        /// Description:  关闭扫码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void EndReader(string station)
        {
            var clientInfo = _tcpClientInfo[station];
            service.CloseReader(clientInfo);
        }

        /// <summary>
        /// Author:
        /// CreateTime:2022-01-19, 10:36:47  
        /// Description:  扫码业务处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public bool scanProcess(string station,string barcode,ref string scanInfo)
        {
            int count = _readConfigInfo.Where(x => x.station == station).Count();
            if (count < 1)
            {
                return false;
            }
            var readConfigInfo = _readConfigInfo.Where(x => x.station == station).FirstOrDefault();
            if (!readConfigInfo.flag)
            {
                scanInfo = barcode;
                return true;
            }
            if (!_tcpClientInfo.ContainsKey(readConfigInfo.station))
            {
                Connection(readConfigInfo.ip, readConfigInfo.port, readConfigInfo.station);
            }
            scanInfo = BeginReader(readConfigInfo.station);
            EndReader(readConfigInfo.station);
            return true;
        }

        /// <summary>
        /// Author:
        /// CreateTime:2022-01-19, 10:36:47  
        /// Description:  获取扫码器配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        public void AddScanConfigure()
        {
            if (_readConfigInfo.Count == 0)
            {
                DataSet ScanConfigure = GetScanConfigure();
                if (ScanConfigure.Tables.Count<=0)
                {
                    return;
                }
                DataTable getScanConfigure = ScanConfigure.Tables[0];
                if (getScanConfigure.Rows.Count > 0)
                {
                    for (int i = 0; i < getScanConfigure.Rows.Count; i++)
                    {
                        ReadConfigInfo readConfigInfo = new ReadConfigInfo();
                        readConfigInfo.station= getScanConfigure.Rows[i]["station"].ToString();
                        readConfigInfo.ip = getScanConfigure.Rows[i]["ip"].ToString();
                        readConfigInfo.port = int.Parse(getScanConfigure.Rows[i]["port"].ToString());
                        readConfigInfo.flag = getScanConfigure.Rows[i]["flag"].ToString() == "1" ? true : false;
                        readConfigInfo.name = getScanConfigure.Rows[i]["description"].ToString();
                        _readConfigInfo.Add(readConfigInfo);
                    }
                }
            }
        }
    }
}
